package com.acme.bankapp.domain.bank;

import java.io.Serializable;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

/**
 * Created by anton on 8/18/14.
 */
public class Client implements Serializable {
    // Fields
    private final String name;
    private final Gender gender;
    private final HashSet<AbstractAccount> accounts;

    public Client(String name, Gender gender, HashSet<AbstractAccount> accounts) {
        this.name = name;
        this.gender = gender;
        this.accounts = accounts;
    }

    public Client(String name, Gender gender, AbstractAccount account) {
        this.name = name;
        this.gender = gender;
        this.accounts = new HashSet<>();
        this.accounts.add(account);
    }

    public String getName() {
        return name;
    }

    public Gender getGender() {
        return gender;
    }


    public int getNbOfAccounts() {
        return accounts.size();
    }

    public AbstractAccount getSingleAccount() {
        if (getNbOfAccounts() == 1) {
            return (AbstractAccount)accounts.toArray()[0];
        }
        return null;
    }

    public double getClientBalance() {
        double clientBalance = 0.0;
        for (AbstractAccount a : this.getAccounts()) {
            clientBalance += a.getBalance();
        }
        return clientBalance;
    }

    public void getClientSalutation() {
        System.out.println(this.gender.getPrefix() + this.name);
    }

    public Set<AbstractAccount> getAccounts() {
        return Collections.unmodifiableSet(accounts);
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (!(obj instanceof Client)) {
            return false;
        }
        Client cl = (Client) obj;

        if (!cl.getName().equals(this.getName())) return false;
        if (!cl.getGender().equals(this.getGender())) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = name.hashCode();
        result = 31 * result + gender.hashCode();
        return result;
    }

    @Override
    public String toString() {

        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("\n===================================" + "\nInformation about the client:" + "\nName: ")
                .append(this.getName()).append("\nGender: ").append(this.getGender()).append("\nAccounts:\n");
        for (AbstractAccount account: accounts) {
            stringBuffer.append(account.toString());
        }
        return stringBuffer.toString();
    }
}
